import React, { Component } from 'react'
import { Toast } from 'antd-mobile'

import {
  Flex,
  List,
  InputItem,
  Picker,
  ImagePicker,
  TextareaItem,
  Modal
} from 'antd-mobile'

import NavHeader from '../../../components/NavHeader'
import HousePackge from '../../../components/HousePackage'

import styles from './index.module.css'
import request from '../../../utils/request'

const alert = Modal.alert

// 房屋类型
const roomTypeData = [
  { label: '一室', value: 'ROOM|d4a692e4-a177-37fd' },
  { label: '二室', value: 'ROOM|d1a00384-5801-d5cd' },
  { label: '三室', value: 'ROOM|20903ae0-c7bc-f2e2' },
  { label: '四室', value: 'ROOM|ce2a5daa-811d-2f49' },
  { label: '四室+', value: 'ROOM|2731c38c-5b19-ff7f' }
]

// 朝向：
const orientedData = [
  { label: '东', value: 'ORIEN|141b98bf-1ad0-11e3' },
  { label: '西', value: 'ORIEN|103fb3aa-e8b4-de0e' },
  { label: '南', value: 'ORIEN|61e99445-e95e-7f37' },
  { label: '北', value: 'ORIEN|caa6f80b-b764-c2df' },
  { label: '东南', value: 'ORIEN|dfb1b36b-e0d1-0977' },
  { label: '东北', value: 'ORIEN|67ac2205-7e0f-c057' },
  { label: '西南', value: 'ORIEN|2354e89e-3918-9cef' },
  { label: '西北', value: 'ORIEN|80795f1a-e32f-feb9' }
]

// 楼层
const floorData = [
  { label: '高楼层', value: 'FLOOR|1' },
  { label: '中楼层', value: 'FLOOR|2' },
  { label: '低楼层', value: 'FLOOR|3' }
]

export default class RentAdd extends Component {
  constructor(props) {
    super(props)

    this.state = {
      // 临时图片地址
      tempSlides: [],

      // 小区的名称和id
      community: {
        name: '',
        id: ''
      },
      // 价格
      price: '',
      // 面积
      size: '',
      // 房屋类型
      roomType: '',
      // 楼层
      floor: '',
      // 朝向：
      oriented: '',
      // 房屋标题
      title: '',
      // 房屋图片
      houseImg: '',
      // 房屋配套：
      supporting: [],
      // 房屋描述
      description: ''
    }
  }

  componentDidMount () {
    this.getC()
  }
  getC (){ // 获取小区页面数据
    const { state } = this.props.history.location
    if (state) {
      this.setState(_ => {
        return {
          community: state.c
        }
      })
    }
  }
  // 取消编辑，返回上一页
  onCancel = () => {
    alert('提示', '放弃发布房源?', [
      {
        text: '放弃',
        onPress: async () => this.props.history.go(-1)
      },
      {
        text: '继续编辑'
      }
    ])
  }
  getValue = (name, value) =>{ // 获取受控组件的信息，绑定到对应的state中
    this.setState(_ => {
      return {
        [name]: value instanceof Array ? value[0] : value
      }
    })
  }
  onSelect  = (val)  =>{ // 获取房屋配置项目
    this.setState(_ => {
      return {
        supporting: val.join('|')
      }
    })
  }
  imgChange = (files, type, index)=> { // 获取图片数据对象
    // files 就等于是普通的updata框上传后得来的文件对象信息
    this.setState(_ => {
      return {
        tempSlides: files
      }
    })
  }
  addHouse = async () => { // 提交事件
    const { // 获取要post的参数，post参数都在请求体中，也就是axios的data属性，params会转化为查询字符串的方式拼接到url上
      tempSlides,
      title,
      description,
      oriented,
      supporting,
      price,
      roomType,
      size,
      floor,
      community
    } = this.state
    // 首先上传图片到服务器，拿着图片对象和服务器进行交换，获取服务器中的图片地址
    if (tempSlides.length > 0) { // 是否有图片
      let houseImg = '' // 保存图片对象
      // 创建formdata对象
      // 将图片对象都加到formdata对象身上
      const form =new FormData()
      tempSlides.forEach(item => form.append('file', item.file))
      // 上传图片
      const { data: res } = await request('/houses/image', 'POST', {data: form}, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      })
      houseImg = res.body.join('|')
      // 该发布了
      const {data: ress} = await request('/user/houses','POST', { data: {
        title,
        description,
        oriented,
        supporting,
        price,
        roomType,
        size,
        floor,
        community: community.id,
        houseImg
      }})
      // 请求后的操作
      if (ress.status === 200) {
        // 发布成功
        Toast.info('发布成功', 1, null, false)
        this.props.history.replace({
          pathname: '/rent',
          state: {
            from: {
              pathname: this.props.location.pathname
            }
          }
        })
      } else {
        Toast.info('服务器偷懒了，请稍后再试~', 2, null, false)
      }
    }
  }
  render() {
    const Item = List.Item
    const { history } = this.props
    const {
      community,
      price,
      roomType,
      floor,
      oriented,
      description,
      tempSlides,
      title,
      size
    } = this.state

    return (
      <div className={styles.root}>
        <NavHeader onLeftClick={this.onCancel}>发布房源</NavHeader>

        <List
          className={styles.header}
          renderHeader={() => '房源信息'}
          data-role="rent-list"
        >
          {/* 选择所在小区 */}
          <Item
            extra={community.communityName || '请输入小区名称'}
            arrow="horizontal"
            onClick={() => history.replace('/rent/search')}
          >
            小区名称
          </Item>
          <InputItem onChange={val => this.getValue('price', val)} type='digit' placeholder="请输入租金/月" extra="￥/月" value={price}>
            租&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;金
          </InputItem>
          <InputItem onChange={val => this.getValue('size', val)} type='digit' placeholder="请输入建筑面积" extra="㎡" value={size}>
            建筑面积
          </InputItem>
          <Picker data={roomTypeData} value={[roomType]} onChange={val => this.getValue('roomType', val)} cols={1}>
            <Item arrow="horizontal">
              户&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;型
            </Item>
          </Picker>

          <Picker onChange={val => this.getValue('floor', val)} data={floorData} value={[floor]} cols={1}>
            <Item arrow="horizontal">所在楼层</Item>
          </Picker>
          <Picker onChange={val => this.getValue('oriented', val)} data={orientedData} value={[oriented]} cols={1}>
            <Item arrow="horizontal">
              朝&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;向
            </Item>
          </Picker>
        </List>

        <List
          className={styles.title}
          renderHeader={() => '房屋标题'}
          data-role="rent-list"
        >
          <InputItem
            onChange={val => this.getValue('title', val)}
            placeholder="请输入标题（例如：整租 小区名 2室 5000元）"
            value={title}
          />
        </List>

        <List
          className={styles.pics}
          renderHeader={() => '房屋图像'}
          data-role="rent-list"
        >
          <ImagePicker
            files={tempSlides}
            onChange={this.imgChange}
            multiple={false}
            className={styles.imgpicker}
          />
        </List>

        <List
          className={styles.supporting}
          renderHeader={() => '房屋配置'}
          data-role="rent-list"
        >
          <HousePackge select onSelect={this.onSelect} />
        </List>

        <List
          className={styles.desc}
          renderHeader={() => '房屋描述'}
          data-role="rent-list"
        >
          <TextareaItem
            clear
            count={50}
            rows={5}
            placeholder="请输入房屋描述信息"
            autoHeight
            onChange={val => this.getValue('description', val)}
            value={description}
          />
        </List>

        <Flex className={styles.bottom}>
          <Flex.Item className={styles.cancel} onClick={this.onCancel}>
            取消
          </Flex.Item>
          <Flex.Item className={styles.confirm} onClick={this.addHouse}>
            提交
          </Flex.Item>
        </Flex>
      </div>
    )
  }
}
